<template>
	<div class="permission-manage-container">
		<!-- 面包屑导航 -->
		<el-breadcrumb separator="/" class="custom-breadcrumb">
			<el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>系统管理</el-breadcrumb-item>
			<el-breadcrumb-item>菜单管理</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 搜索区域 -->
		<el-form :inline="true" :model="queryInfo" class="search-form">
			<el-form-item label="权限名">
				<el-input v-model="queryInfo.name" placeholder="请输入权限名" clearable style="width: 150px;" />
			</el-form-item>

			<el-form-item label="权限类型">
				<el-select v-model="queryInfo.type" placeholder="请选择权限类型" clearable style="width: 200px;">
					<el-option label="目录" value="1" />
					<el-option label="菜单" value="2" />
					<el-option label="按钮" value="3" />
				</el-select>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="queryDataList">搜索</el-button>
				<el-button type="success" @click="handleCreate">新增权限</el-button>
				<el-button type="danger" @click="handleBatchDelete"
					:disabled="multipleSelection.length === 0">批量删除</el-button>
			</el-form-item>
		</el-form>

		<!-- 表格区域 -->
		<el-table :data="dataList" row-key="id" style="width: 100%" @selection-change="handleSelectionChange" border
			:loading="tableLoading">
			<el-table-column type="selection" width="55" />
			<el-table-column prop="id" label="ID" width="85" />
			<el-table-column prop="name" label="权限名称" width="200" />
			<el-table-column prop="type" label="权限类型" :formatter="formatType" />
			<el-table-column prop="url" label="访问地址" />
			<el-table-column prop="percode" label="权限代码" />
			<el-table-column prop="parentId" label="父节点ID" />
			<el-table-column prop="sort" label="显示顺序" />

			<el-table-column label="操作" width="200">
				<template #default="scope">
					<el-button type="primary" size="small" @click="update(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 新增和修改对话框 -->
		<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancel">
			<el-form :model="permissionData" :rules="rules" label-width="100" ref="formRef">
				<el-form-item label="权限名" prop="name">
					<el-input v-model="permissionData.name" autocomplete="off" placeholder="请输入权限名" />
				</el-form-item>

				<el-form-item label="权限类型" prop="type">
					<el-select v-model="permissionData.type" autocomplete="off" placeholder="请选择权限类型"
						style="width: 200px;">
						<el-option label="目录" value="1" />
						<el-option label="菜单" value="2" />
						<el-option label="按钮" value="3" />
					</el-select>
				</el-form-item>

				<el-form-item label="url" prop="url">
					<el-input v-model="permissionData.url" autocomplete="off" placeholder="请输入url" />
				</el-form-item>

				<el-form-item label="权限代码" prop="percode">
					<el-input v-model="permissionData.percode" autocomplete="off" placeholder="请输入权限代码" />
				</el-form-item>

				<el-form-item label="父节点ID" prop="parentId">
					<el-input v-model="permissionData.parentId" autocomplete="off" placeholder="请输入父节点ID" />
				</el-form-item>

				<el-form-item label="显示顺序" prop="sort">
					<el-input v-model.number="permissionData.sort" autocomplete="off" placeholder="请输入显示顺序" />
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button @click="cancel">取消</el-button>
					<el-button type="primary" @click="confirm" :loading="formLoading">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 分页区域 -->
		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
			:current-page="queryInfo.pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="queryInfo.pageSize"
			layout="total, sizes, prev, pager, next, jumper" :total="total" style="margin-top: 15px;" />
	</div>
</template>

<script setup>
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';
	import {
		getCurrentInstance,
		onMounted,
		reactive,
		ref,
		toRefs
	} from 'vue';

	// 搜索参数
	const queryInfo = reactive({
		name: '',
		type: '',
		pageNum: 1,
		pageSize: 10
	});

	// 表格数据和状态
	const total = ref(0);
	const dataList = ref([]);
	const tableLoading = ref(false);
	const multipleSelection = ref([]);
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;

	// 表单相关
	const dialogFormVisible = ref(false);
	const title = ref('新增权限');
	const permissionData = ref({
		id: '',
		name: '',
		type: '',
		url: '',
		percode: '',
		parentId: '',
		sort: ''
	});
	const formRef = ref(null);
	const formLoading = ref(false);

	// 表单验证规则
	const rules = {
		name: [{
			required: true,
			message: '请输入权限名',
			trigger: 'blur'
		}],
		type: [{
			required: true,
			message: '请选择权限类型',
			trigger: 'change'
		}],
		sort: [{
			type: 'number',
			message: '请输入有效的数字',
			trigger: 'blur'
		}]
	};

	// 格式化权限类型
	const formatType = (row, column, cellValue) => {
		const typeMap = {
			'1': '目录',
			'2': '菜单',
			'3': '按钮'
		};
		return typeMap[cellValue] || cellValue;
	};

	// 查询数据列表
	const queryDataList = async () => {
		tableLoading.value = true;
		try {
			const resp = await axios.get('permission/page', {
				params: queryInfo
			});
			if (resp.code === 200) {
				console.log(resp);
				dataList.value = resp.data.list;
				total.value = resp.data.total.length;
			} else {
				ElMessage.error(resp.data.message || '查询失败');
			}
		} catch (error) {
			ElMessage.error('查询失败：' + error.message);
		} finally {
			tableLoading.value = false;
		}
	};

	// 新增权限
	const handleCreate = () => {
		title.value = '新增权限';
		dialogFormVisible.value = true;
		// 重置表单数据和验证状态
		resetForm();
	};

	// 编辑权限
	const update = (row) => {
		title.value = '编辑权限';
		dialogFormVisible.value = true;
		// 使用深拷贝避免直接修改原数据
		permissionData.value = JSON.parse(JSON.stringify(row));
	};

	// 提交表单
	const confirm = async () => {
		// 表单验证
		await formRef.value.validate((valid) => {
			if (!valid) return false;
		});

		formLoading.value = true;
		try {
			let resp;
			if (permissionData.value.id) {
				// 更新操作
				resp = await axios.put('permission', permissionData.value);
			} else {
				// 新增操作
				resp = await axios.post('permission', permissionData.value);
			}

			if (resp.data.code === 200) {
				ElMessage.success(permissionData.value.id ? '修改成功' : '新增成功');
				dialogFormVisible.value = false;
				queryDataList();
			} else {
				ElMessage.error(resp.data.message || (permissionData.value.id ? '修改失败' : '新增失败'));
			}
		} catch (error) {
			ElMessage.error((permissionData.value.id ? '修改失败：' : '新增失败：') + error.message);
		} finally {
			formLoading.value = false;
		}
	};

	// 取消操作
	const cancel = () => {
		dialogFormVisible.value = false;
		resetForm();
	};

	// 重置表单
	const resetForm = () => {
		permissionData.value = {
			id: '',
			name: '',
			type: '',
			url: '',
			percode: '',
			parentId: '',
			sort: ''
		};

		// 重置表单验证状态
		if (formRef.value) {
			formRef.value.resetFields();
		}
	};

	// 删除权限
	const remove = (id) => {
		ElMessageBox.confirm(
			'此操作将永久删除该权限, 是否继续?',
			'提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		).then(async () => {
			try {
				const resp = await axios.delete(`permission/${id}`);
				if (resp.data.code === 200) {
					ElMessage.success('删除成功');
					queryDataList();
				} else {
					ElMessage.error(resp.data.message || '删除失败');
				}
			} catch (error) {
				ElMessage.error('删除失败：' + error.message);
			}
		}).catch(() => {
			ElMessage.info('已取消删除');
		});
	};

	// 批量删除
	const handleBatchDelete = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择需要删除的权限');
			return;
		}

		ElMessageBox.confirm(
			`确定要删除选中的 ${multipleSelection.value.length} 条权限数据吗?`,
			'提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		).then(async () => {
			try {
				const resp = await axios.delete('permission', {
					params: {
						ids: multipleSelection.value.join(',')
					}
				});

				if (resp.data.code === 200) {
					ElMessage.success('批量删除成功');
					queryDataList();
					multipleSelection.value = [];
				} else {
					ElMessage.error(resp.data.message || '批量删除失败');
				}
			} catch (error) {
				ElMessage.error('批量删除失败：' + error.message);
			}
		}).catch(() => {
			ElMessage.info('已取消批量删除');
		});
	};

	// 多选变更
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => item.id);
	};

	// 分页相关
	const handleSizeChange = (size) => {
		queryInfo.pageSize = size;
		queryDataList();
	};

	const handleCurrentChange = (num) => {
		queryInfo.pageNum = num;
		queryDataList();
	};

	// 初始化加载
	onMounted(() => {
		queryDataList();
	});
</script>

<style scoped>
	.custom-breadcrumb {
		padding: 12px 16px;
		background-color: #ffffff;
		border-radius: 4px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
	}

	.search-form {
		margin: 15px 0;
		padding: 15px;
		background-color: #ffffff;
		border-radius: 4px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
	}

	.dialog-footer {
		display: flex;
		justify-content: flex-end;
	}
</style>